<?php
namespace App\Model;

class User extends Model
{
    use \HyperfSanctum\Tokens;
    
    // 表名
    protected $table = 'users';
    
    // 保护属性
    protected $guarded = [];
    
    protected $attributes = [
        'user_id'        => 0,
        'user_all'       => '[]',
        'shop_id'        => 0,
        'level_id'       => 0,
        'money'          => 0,
        'money_pay'      => 0,
        'money_all'      => 0,
        'money_user'     => 0,
        'money_full'     => 0,
        'money_full_all' => 0,
        'money_discount' => 0,
        "money_wallet_red"=> 0,
        "money_wallet"   => 0
    ];
    
    // 格式
    protected $casts = [
        'user_all' => 'array'
    ];
    
    protected $hidden = [
        'password'
    ];
    
    protected $dateFormat = 'U';
    
    // 我的等级
    public function level()
    {
        return $this->belongsTo(Level::class, 'level_id');
    }
    
    // 上级用户
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
    
    // 下级用户
    public function userChild()
    {
        return $this->hasMany(User::class, 'user_id');
    }
    
    // 所属店铺
    public function shop()
    {
        return $this->belongsTo(Shop::class, 'shop_id');
    }
    
    // 我的店铺
    public function shopMy()
    {
        return $this->hasOne(Shop::class, 'user_id');
    }
    
    // 创建事件
    public function creating()
    {
        // 密码加密
        $this->password = password_hash((string) $this->password, PASSWORD_DEFAULT);
    }
    
    // 更新事件
    public function updating()
    {
        // 密码发现变动
        if(password_needs_rehash((string) $this->password, PASSWORD_DEFAULT))
        {
            $this->creating();
        }
    }
}